<template>
	<view>
		<nav-bar title="确认订单"></nav-bar>
		<scroll-view scroll-y :style="{ height: scrollHeight }">
			<view :class="chooseAddress.choice?'address-box':'address-box choice'"
				v-if="chooseAddress && chooseAddress.receiverName">
				<view class="person-box">
					<view class="user-name">{{ chooseAddress.receiverName }}</view>
					<view class="phone">{{ chooseAddress.phoneNumber }}</view>
					<view class="address-btn" @click="clickAddressManage">地址管理</view>
				</view>
				<view class="address">{{ chooseAddress.address }}</view>
			</view>
			<view v-else class="address-box">
				<view class="person-box">
					<view class="user-name">您还没有添加收货地址</view>
					<view class="address-btn" @click="clickAddressManage">地址管理</view>
				</view>
			</view>
			<view class="goods-list">
				<goods-list :goodsList="goodsList" :showSale="false"></goods-list>
			</view>
			<view class="send-type">
				<view class="send-item">
					<view class="item-label">配送方式</view>
					<view class="item-value">
						<view class="common" v-for="(item, index) in sendType" :key="index"
							@click="sendClick(item, index)">
							<uni-icons :type="curIndex === index ? 'circle-filled' : 'circle'" size="25"
								color="#0b3f35"></uni-icons>
							<text class="word">{{ item }}</text>
						</view>
					</view>
				</view>
				<!-- <view class="desc-text">
					配送说明配送说明配送说明
				</view> -->
				<u-textarea style="background-color: #f2f2f2 !important;" placeholder="请输入配送说明"
					v-model="remark"></u-textarea>
				<!-- <input class="desc-text" type="text" v-model="remark" /> -->
				<view class="send-item">
					<view class="item-label">配送费</view>
					<view class="item-value">
						<text class="num">￥</text><text class="money">{{ deliveryScope }}</text>
					</view>
				</view>
				<view class="send-item">
					<view class="item-label">支付方式</view>
					<view class="item-value">
						<view class="value-btn">
							<image class="btn-img" :src="baseIconUrl + 'icon_weixin.png'" mode="aspectFill" />
						</view>
						<view class="pay">微信支付</view>
					</view>
				</view>
				<!-- <view class="send-item">
					<view class="item-label">订单编号</view>
					<view class="item-value">82735027530239758</view>
				</view> -->
			</view>
		</scroll-view>
		<view class="bottom-box" :style="{ paddingBottom: safeHeight + 5 + 'px' }">
			<view class="price-box">
				<text class="price-icon">￥</text>{{ allAccount }}
			</view>
			<view class="confirm-btn" @click="submitOrder">提交订单</view>
		</view>
	</view>
</template>

<script>
	import {
		baseImgUrl,
		baseIconUrl
	} from '@/config'
	import GoodsList from '../components/goodsList'
	export default {
		name: 'ConfirmOrder',
		components: {
			GoodsList
		},
		data() {
			return {
				baseImgUrl,
				baseIconUrl,
				remark: '暂无配送说明',
				scrollHeight: '',
				safeHeight: '',
				chooseAddress: {},
				goodsList: [],
				curIndex: 0,
				storeId: '',
				total: '',
				deliveryScope: '',
				sendType: ['普通配送', '加急配送', '无需配送']
			}
		},
		computed: {
			allAccount() {
				const price = this.goodsList.reduce((price, item) => {
					return price + item.count * item.price
				}, 0)
				let totalPrice = (Number(price) + Number(this.deliveryScope)).toFixed(2)
				this.total = totalPrice
				return totalPrice
			}
		},
		async onLoad(options) {
			console.log('订单结算列表--->', this.$store.getters.settleList)
			this.storeId = options.storeId
			this.deliveryScope = this.$store.getters.deliveryScope
			this.safeHeight = this.$store.getters.heightData.safeHeight
			await this.getGoodsList(this.$store.getters.settleList)
		},
		async onShow() {
			await this.getAddress()
		},
		onReady() {
			this.getBottomBoxHeight()
		},
		methods: {
			async submitOrder() {
				const newArr = this.goodsList.map((item) => {
					item.goodPrice = item.retailPrice
					item.goodCount = item.count
					item.storeGoodId = item.id
					item.supplierGoodId = item.goodId
					return item
				})
				const data = {
					storeId: this.storeId,
					remark: this.remark,
					receiveName: this.chooseAddress.receiverName,
					receivePhonenum: this.chooseAddress.phoneNumber,
					receiveAddress: this.chooseAddress.address,
					payMoney: this.total,
					fxOrderItemList: this.goodsList,
					deliveryType: this.curIndex + 1
				}
				console.log(data);
				if (this.chooseAddress.receiverName && this.chooseAddress.choice) {
					const res = await this.$POST('/fx/order', data)
					if (res.code == 200) {
						console.log(res)
						wx.requestPayment({
							appid: res.data.data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
							nonceStr: res.data.data.nonceStr, // 随机字符串
							package: res.data.data.package, // 固定值
							partnerid: res.data.data.partnerid, // 微信支付商户号
							timeStamp: res.data.data.timestamp, // 时间戳（单位：秒）
							paySign: res.data.data.paySign, // 签名，这里用的 MD5/RSA 签名
							signType: res.data.data.signType,
							success: async (wxres) => {
								const shop_car = {
									cartList: [],
									selectCartList: []
								}
								uni.showToast({
									icon: 'success',
									title: '支付成功',
									duration: 2000
								})
								let wxData = {
									...data,
									id: res.data.data.orderNum
								}
								const res2 = await this.$POST('/fx/order/createOrder', wxData)
								console.log(res2);
								this.$emit('SET_SHOP_CAR', shop_car)
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/order'
									})
								}, 2000)
								console.log(wxres, '支付成功')
							},
							fail: err => {
								uni.showToast({
									icon: 'none',
									title: '支付失败',
									duration: 2000
								})
								console.log(err)
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 2000
						})
					}
				} else if (this.chooseAddress.receiverName && !this.chooseAddress.choice) {
					uni.showToast({
						icon: 'none',
						title: '当前地址不可配送',
						duration: 2000
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: '请选择收货地址',
						duration: 2000
					})
					setTimeout(() => {
						uni.navigateTo({
							url: `/subPages/store/myAddress?storeId=${this.storeId}`
						})
					}, 2000)
				}

			},
			getBottomBoxHeight() {
				this.$nextTick(() => {
					// 创建查询对象
					setTimeout(() => {
						const query = uni.createSelectorQuery().in(this)

						// 选择我们想要的元素
						query.select('.bottom-box').boundingClientRect(data => {
							// data是一个包含元素尺寸信息的对象
							if (data) {
								// 获取元素高度
								const height = data.height
								this.scrollHeight = this.$store.getters.heightData
									.noTabMainHeight - height + this.safeHeight + 'px'
							}
						}).exec()
					}, 200)
				})
			},
			async getAddress() {
				// 是否可以配送
				const res = await this.$GET(`/fx/address/getDefaultList?id=${this.storeId}`)
				if (res.code == 200) {
					let zt = res.data.some(t => t.isDefault == 0)
					if (res.data.length > 0 && zt) {
						res.data.forEach((el) => {
							if (el.isDefault === 0) {
								this.chooseAddress = el
							}
						})
					} else if (res.data.length > 0) {
						this.chooseAddress = res.data[0]
					} else {
						this.chooseAddress = {}
					}
					console.log('皮', this.chooseAddress)
				} else if (res.code == 401 && res.msg == "获取用户ID异常") {
					uni.navigateTo({
						url: '/subPages/home/login'
					})
				}
			},
			getGoodsList(data) {
				console.log(data)
				const userInfo = this.$store.getters.userInfo
				this.goodsList = data.map((item) => {
					item.name = item.goodName
					item.img = item.goodImg
					item.price = userInfo.isMember && userInfo.isMember == 2 ? item.memberPrice : item.retailPrice
					item.carNum = item.count
					return item
				})
			},
			clickAddressManage() {
				uni.navigateTo({
					url: `/subPages/store/myAddress?storeId=${this.storeId}`
				})
			},
			//配送点击事件
			sendClick(val, index) {
				this.curIndex = index
				if (index === 0) {
					this.deliveryScope = this.$store.getters.deliveryScope
				} else if (index === 1) {
					this.deliveryScope = this.$store.getters.deliveryScope2
				} else if (index === 2) {
					this.deliveryScope = 0
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.address-box {
		margin: 20rpx 28rpx;
		padding: 20rpx 24rpx;
		border-radius: 12rpx;
		background-color: #FFF;

		.person-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 8rpx;
			font-size: 28rpx;

			.phone {
				flex: 1;
				margin: 0 20rpx;
			}

			.address-btn {
				color: #126352;
			}
		}

		.address {
			font-size: 24rpx;
			line-height: 44rpx;
			color: #808080;
		}
	}

	.choice {
		color: #ddd !important;
	}

	.goods-list {
		margin: 20rpx 28rpx;
	}

	.send-type {
		margin: 20rpx 28rpx;
		padding: 20rpx 24rpx;
		border-radius: 12rpx;
		background-color: #FFF;

		.send-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0;

			.item-value {
				display: flex;
				align-items: center;

				.num,
				.money {
					display: block;
					font-size: 28rpx;
					color: #0b3f35;
				}

				.common {
					display: flex;
					align-items: center;
					margin-left: 10rpx;
				}

				.word {
					margin-left: 16rpx;
				}
			}

			.value-btn {
				width: 40rpx;
				height: 40rpx;
			}

			.btn-img {
				width: 100%;
				height: 100%;
			}

			.pay {
				margin-left: 10rpx;
			}
		}
	}

	.bottom-box {
		position: fixed;
		bottom: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 28rpx 0;
		width: 100%;
		border-top: 2rpx solid rgba(0, 0, 0, .1);
		background-color: #FFF;

		.price-box {
			font-size: 50rpx;
			color: #FA462C;

			.price-icon {
				font-size: 30rpx;
			}
		}

		.confirm-btn {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 288rpx;
			height: 80rpx;
			border-radius: 40rpx;
			font-size: 30rpx;
			color: #FFF;
			background-color: #0b3f35;
		}
	}

	.desc-text {
		width: 100%;
		padding: 30rpx;
		border-radius: 8rpx;
		background: #F2F2F2;
		max-height: 6em;
		/* 限制最大高度为三行文本 */
		line-height: 2em;
		/* 每行文本的高度 */
	}
</style>